<!--
 * @Author: hepch
 * @Date: 2021-08-09 09:04:39
 * @LastEditors: 杨光辉(GerhardYang)
 * @LastEditTime: 2021-09-09 17:35:15
 * @Description: file content
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->
<template>
  <div id="search-stake">
    <a-card class="searchstake-card" size="small" title="桩号查询">
      <a slot="extra" href="#">
        <a-select
          style="width: 90px; margin-right: 150px"
          size="small"
          v-model="searchStakesBytype"
          @change="changeSearchTypes"
        >
          <a-select-option value="locationStake"> 定位桩号 </a-select-option>
          <a-select-option value="computeStake"> 桩号计算</a-select-option>
        </a-select>
        <a-icon type="close" @click="closeCard" />
      </a>
      <div v-if="searchStakesBytype == 'locationStake'">
        <a-form class="searchstake-from" style="width: 100%">
          <a-form-item
            label="路线"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            style="margin-bottom: 0 !important"
          >
            <a-input-group>
              <a-select
                class="road-select"
                style="width: 190px"
                show-search
                autoFocus
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                v-model="roadcode"
                size="small"
                @search="handleSearch"
                @change="onSelectCode"
                placeholder="路线编码"
              >
                <a-select-option v-for="d in roadList" :key="d.id">
                  {{ d.properties[roadlayer.searchFieldname] }}
                </a-select-option></a-select
              >
              <a-select
                size="small"
                v-model="time"
                @change="onChangeYear"
                class="year-select"
              >
                <!-- <a-select-option value="LDXLH">路段序列</a-select-option> -->
                <a-select-option v-for="d in StakeQLayes" :key="d.id">
                  {{ d.id }}
                </a-select-option>
              </a-select>
            </a-input-group>
          </a-form-item>
          <a-form-item
            label="桩号"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            style="margin-bottom: 0 !important"
          >
            <a-input-group compact>
              <a-input-number
                size="small"
                style="width: 225px; text-align: center"
                placeholder="里程（km）"
                :precision="2"
                step="1"
                :min="0"
                v-model="kilometer"
              >
              </a-input-number>
              <a-button @click="searchStake" size="small">
                <a-icon type="search" />
              </a-button>
            </a-input-group>
          </a-form-item>
        </a-form>
      </div>
      <div v-if="searchStakesBytype == 'computeStake'">
        <a-form class="searchstake-from" style="width: 100%">
          <a-form-item
            label="路段"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            style="margin-bottom: 0 !important"
          >
            <a-input-group compact>
              <a-select
                class="road-select"
                style="width: 130px"
                show-search
                autoFocus
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                v-model="roadcode"
                size="small"
                @search="handleSearchRocadCode"
                @change="onSelectRoadCode"
                placeholder="路段编码"
                @focus="loseblur()"
              >
                <a-select-option v-for="d in roadList" :key="d.id">
                  {{ d.properties.LDBM }}
                </a-select-option></a-select
              >
              <a-select
                size="small"
                v-model="time"
                @change="onChangeYear"
                class="year-select"
              >
                <!-- <a-select-option value="LDXLH">路段序列</a-select-option> -->
                <a-select-option v-for="d in StakeQLayes" :key="d.id">
                  {{ d.id }}
                </a-select-option>
              </a-select>
              <a-button
                size="small"
                @click="pickup()"
                :disabled="ispick"
                title="在线上选点"
              >
                <icon-font type="icon-tuding1" />
              </a-button>
            </a-input-group>
          </a-form-item>
          <a-form-item
            v-if="false"
            label="距离"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            style="margin-bottom: 0 !important"
          >
            <a-input-group compact>
              <a-input-number
                size="small"
                style="width: 225px; text-align: center"
                placeholder="距路段起始端点里程（km）"
                :precision="2"
                step="1"
                :min="0"
                @change="computeStakeByDis"
                v-model="kilometerTostart"
              >
              </a-input-number>
              <a-button @click="computeStakeByDis" size="small">
                <a-icon type="calculator" />
              </a-button>
            </a-input-group>
          </a-form-item>
          <a-form-item
            label="桩号"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            style="margin-bottom: 0 !important"
          >
            <a-input-group compact>
              <a-input-number
                disabled
                size="small"
                placeholder="里程（km）"
                :precision="2"
                step="1"
                v-model="kilometer"
                :style="{
                  color: kilometer != undefined ? 'red' : 'gray',
                }"
                style="width: '225px'; text-align: center"
              >
              </a-input-number>
              <a-button @click="searchStake" size="small" v-if="false">
                <a-icon type="search" />
              </a-button>
            </a-input-group>
          </a-form-item>
        </a-form>
      </div>
    </a-card>
    <search-stakes-result ref="SearchStakesResult" />
  </div>
</template>
<script>
import { Icon } from "ant-design-vue";
// 自定义图标
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: "./iconfont/iconfont.js",
});
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};
import {
  lineString,
  along,
  length,
  nearestPointOnLine,
  point,
  lineSlice,
} from "@turf/turf";
import {
  dataGetRoadBySQLParameters,
  dataGetFeaturesBySQL,
} from "@/utils/http/iserverQuery";
import L from "leaflet";
import SearchStakesResult from "./SearchStakesResult.vue";
export default {
  components: { SearchStakesResult, IconFont },
  data() {
    return {
      formItemLayout,
      roadList: [],
      roadcode: undefined,
      roadResultCode: null,
      stakeQueryLayer: null,
      linefeature: null,
      minkm: 0,
      currentroad: null,
      kilometer: 0,
      time: null,
      roadlayer: null,
      stakelayer: null,
      startStakeNum: null,
      searchStakesBytype: "locationStake",
      kilometerTostart: undefined,
      pt: undefined,
      ispick: true,
    };
  },
  computed: {
    searchstakesFeatureGroup() {
      return this.$store.state.searchstakesFeatureGroup;
    },
    StakeQLayes() {
      return this.$store.state.config.StakeQLayes;
    },

    map() {
      return this.$store.state.map;
    },
  },
  watch: {
    //释放点击事件
    pt: function () {
      if (this.pt) {
        this.map.off("click");
        this.pt = undefined;
        L.DomUtil.removeClass(this.map._container, "leaflet-cursor-pointer");
      }
    },
  },
  mounted() {
    this.onload();
  },
  methods: {
    //桩号定位和桩号计算切换事件
    changeSearchTypes(value) {
      this.searchStakesBytype = value;
      this.roadList = [];
      this.roadcode = undefined;
      this.ispick = true;
      this.kilometer = undefined;
    },
    //拾取一个点
    pickup() {
      this.kilometer = undefined;
      let self = this;
      L.DomUtil.addClass(this.map._container, "leaflet-cursor-pointer");
      this.map.on("click", function (e) {
        let pt = point([e.latlng.lng, e.latlng.lat]);
        self.pt = pt;
        let snapped = nearestPointOnLine(self.turfline, pt);
        self.$refs.SearchStakesResult.pointToMap(snapped);
        console.log(snapped);
        var stop = point([
          snapped.geometry.coordinates[0],
          snapped.geometry.coordinates[1],
        ]);
        var sliced = lineSlice(self.linestartpoint, stop, self.turfline);
        self.computeStakeByDis(length(sliced));
      });
    },
    loseblur() {
      this.ispick = true;
    },
    computeStakeByDis(length) {
      this.linefeature
        ? (this.kilometer =
            length +
            Number(
              this.linefeature.properties[this.roadlayer.startStakeFieldname]
            ))
        : this.$message.info("请先匹配路段编码");
    },
    //除去字符串前后空格
    trim(inputStr) {
      return inputStr.replace(/^\s*|\s*$/g, "");
    },
    //关闭面板
    closeCard() {
      this.$parent.isSearchStake = false;
      this.searchstakesFeatureGroup.clearLayers();
    },
    //年报数据选择
    onChangeYear(value) {
      let data = this.StakeQLayes.filter((item) => item.id === value)[0];
      this.roadlayer = data.roadlayer;
      this.stakelayer = data.stakelayer;
      this.time = value;
      this.kilometer = undefined;
      this.roadList = [];
    },
    //初始化数据
    onload() {
      let data = this.StakeQLayes[0];
      this.time = this.StakeQLayes[0].id;
      this.roadlayer = data.roadlayer;
      this.stakelayer = data.stakelayer;
    },
    //run the find-road and stakes method
    searchStake() {
      if (this.roadcode) this.queryroadByCodeStake();
    },
    //重置
    reset() {
      this.roadList = [];
      this.roadcode = null;
      this.linefeature = null;
      this.searchstakesFeatureGroup.clearLayers();
    },
    //模糊匹配路段编码
    handleSearchRocadCode(value) {
      this.fetch(value);
    },
    //开始模糊匹配
    handleSearch(value) {
      this.fetch(value);
    },
    //模糊匹配
    fetch(value) {
      let self = this;
      this.roadList = [];
      if (this.timeout) {
        clearTimeout(this.timeout);
        this.timeout = null;
      }
      function fake() {
        self.matchroadcode(value);
      }
      this.timeout = setTimeout(fake, 300);
    },
    onSelectRoadCode(value) {
      this.kilometer = undefined;
      this.ispick = false;
      this.linefeature = this.roadList.filter((item) => item.id == value)[0];
      this.linestartpoint = point([
        this.linefeature.geometry.coordinates[0][1],
        this.linefeature.geometry.coordinates[0][0],
      ]);
      this.turfline = lineString(this.linefeature.geometry.coordinates);
      console.log(this.linefeature);
      let linecoordinates = this.linefeature.geometry.coordinates;
      this.linefeature.geometry.type == "LineString"
        ? this.$refs.SearchStakesResult.route2map([linecoordinates])
        : this.$refs.SearchStakesResult.route2map(linecoordinates);
      // result.features.features[0].geometry.coordinates
      // this.roadcode =
      //   this.linefeature.properties[this.roadlayer.searchFieldname];
      // this.minkm = Number(
      //   this.linefeature.properties[this.roadlayer.startStakeFieldname]
      // );
      // this.kilometer = this.minkm;
    },
    //选中路线BM
    onSelectCode(value) {
      this.linefeature = this.roadList.filter((item) => item.id == value)[0];
      this.roadcode =
        this.linefeature.properties[this.roadlayer.searchFieldname];
      this.minkm = Number(
        this.linefeature.properties[this.roadlayer.startStakeFieldname]
      );
      this.kilometer = this.minkm;
    },
    findlocationXY(linecoordinates) {
      let line = lineString(linecoordinates);
      let options = {};
      let locationbykilometres = along(
        line,
        this.kilometer - this.startStakeNum,
        options
      );
      return locationbykilometres;
    },
    async queryroadByCodeStake() {
      this.searchstakesFeatureGroup.clearLayers();
      let sql = `${this.roadlayer.searchFieldname}='${this.roadcode}' AND ${this.kilometer}>=${this.roadlayer.startStakeFieldname} AND ${this.kilometer}<=${this.roadlayer.endStakeFieldname} `;
      let datasetNames = [
        `${this.roadlayer.datasource}:${this.roadlayer.dataset}`,
      ];

      let params = dataGetRoadBySQLParameters(datasetNames, sql);
      let dataUrl = this.roadlayer.dataurl;
      let result = await dataGetFeaturesBySQL(dataUrl, params);
      //let resultstake = await this.findNearStake();

      // if (this.dealresult(resultstake, "GLZH")) {
      //   this.$refs.SearchStakesResult.featuresToMap(resultstake.features);
      // }
      if (this.dealresult(result)) {
        let linecoordinates = result.features.features[0].geometry.coordinates;
        this.startStakeNum =
          result.features.features[0].properties[
            this.roadlayer.startStakeFieldname
          ];
        result.features.features[0].geometry.type == "LineString"
          ? this.$refs.SearchStakesResult.route2map([linecoordinates])
          : this.$refs.SearchStakesResult.route2map(linecoordinates);
        this.$refs.SearchStakesResult.pointToMap(
          this.findlocationXY(linecoordinates)
        );
      }
    },
    //deal data of queryroad and run the querRoadByCode()
    matchroadcode(inputStr) {
      this.searchstakesFeatureGroup.clearLayers();
      inputStr = this.trim(inputStr);
      this.queryRoadByCode(inputStr);
    },
    async findNearStake() {
      let sql = `${this.roadlayer.searchFieldname}='${this.roadcode}' AND ${
        this.stakelayer.stakeFieldname
      }>${parseInt(this.kilometer) - 1} AND ${this.stakelayer.stakeFieldname}<${
        parseInt(this.kilometer) + 2
      }`;
      let datasetNames = [
        `${this.stakelayer.datasource}:${this.stakelayer.dataset}`,
      ];

      let params = dataGetRoadBySQLParameters(datasetNames, sql);
      let dataUrl = this.stakelayer.dataurl;
      let result = await dataGetFeaturesBySQL(dataUrl, params);
      return result;
    },
    //路线或者路段匹配
    async queryRoadByCode(inputStr) {
      let sql = "";

      sql = `LDXLH = '001' AND  ${this.roadlayer.searchFieldname}  LIKE  '%${inputStr}%'  `;
      if (this.searchStakesBytype == "computeStake") {
        sql = `LDBM LIKE  '%${inputStr}%'  `;
      }
      let datasetNames = [
        `${this.roadlayer.datasource}:${this.roadlayer.dataset}`,
      ];
      // let arrayfileds = [this.roadlayer.searchFieldname];
      let params = dataGetRoadBySQLParameters(datasetNames, sql);
      let dataUrl = this.roadlayer.dataurl;
      let result = await dataGetFeaturesBySQL(dataUrl, params);
      if (this.dealresult(result, "match")) {
        this.roadList = result.features.features;
      }
    },

    dealresult(result, type) {
      if (!result) {
        this.$message.destroy();
        this.$message.error("服务/查询参数错误，请联系管理员");
        return false;
      } else if (result.totalCount < 1) {
        if (type == "GLZH") {
          this.$message.destroy();
          this.$message.warning("没有匹配到附近的公路桩");
          return false;
        }
        if (type == "match") {
          this.$message.destroy();
          //this.$message.warning("暂无匹配数据,请检查输入是否正确");
          return false;
        }
        this.$message.destroy();
        this.$message.warning("查询桩号不在范围内");
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>
<style lang="less">
#search-stake {
  .searchstake-card {
    width: 344px;
    .ant-card-body {
      // padding: 10px !important;
      padding-left: 24px !important;
      .searchstake-from {
        width: 100%;
        padding: 2px;
        background-color: #fff;
        border-radius: 1rem;
        padding: 1px;
        border-radius: 1rem;

        .road-select {
          .ant-select-selection {
            border-top-right-radius: 0px;
            border-bottom-right-radius: 0px;
          }
        }
        .year-select {
          .ant-select-selection {
            border-top-left-radius: 0px;
            border-bottom-left-radius: 0px;
          }
        }

        .ant-form-item-label {
          width: auto;
        }
        .ant-form-item-control-wrapper {
          width: auto;
        }
      }
    }
  }
}
</style>
